package net.mohas.docsearch.view;

import java.awt.Desktop;
import java.awt.EventQueue;
import java.io.File;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;

import net.mohas.docsearch.controller.DatabaseOperation;
import net.mohas.docsearch.controller.Indexing;
import net.mohas.docsearch.controller.Searching;
import net.mohas.docsearch.controller.Searching.HasilCari;
import net.mohas.docsearch.controller.TextOperation;
import net.mohas.docsearch.model.CustomEnglishAnalyzer;
import net.mohas.docsearch.model.CustomIndonesianAnalyzer;
import cern.colt.matrix.DoubleMatrix2D;

/**
 *
 * @author Muhammad
 * 
 */
public class FrameUtama extends JFrame {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1892707361946767721L;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					FrameUtama frame = new FrameUtama();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/** Creates new form FrameUtama */
    public FrameUtama() {

        // pengaturan lookandfeel windows
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (Exception e) {}

        FileFilter tipeberkas = new FileFilter() {

            @Override
            public boolean accept(File f) {
                boolean boleh = false;
                if (f.isDirectory()
                        || f.getName().toLowerCase().endsWith("txt")
                        || f.getName().toLowerCase().endsWith("rtf")
                        || f.getName().toLowerCase().endsWith("pdf")
                        || f.getName().toLowerCase().endsWith("ods")
                        || f.getName().toLowerCase().endsWith("odt")
                        || f.getName().toLowerCase().endsWith("odp")
                        || f.getName().toLowerCase().endsWith("doc")
                        || f.getName().toLowerCase().endsWith("xls")
                        || f.getName().toLowerCase().endsWith("ppt")
                        || f.getName().toLowerCase().endsWith("docx")
                        || f.getName().toLowerCase().endsWith("xlsx")
                        || f.getName().toLowerCase().endsWith("pptx")
                        || f.getName().toLowerCase().endsWith("htm")
                        || f.getName().toLowerCase().endsWith("html")) {
                    boleh = true;
                }

                return boleh;
            }

            @Override
            public String getDescription() {
                String tipe = "Text Documents (*.txt,*.rtf,*.pdf,*.odt,*.ods,*.odp,*.doc,*.ppt,*.xls,*.docx,*.pptx,*.xlsx,*.htm,*.html)";
                return tipe;
            }
        };

        // JFileChooser
        pilihfolder = new JFileChooser();
        pilihfolder.setFileFilter(tipeberkas);
        pilihfolder.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        pilihfolder.setMultiSelectionEnabled(true);
        pilihfolder.setDialogTitle("Choose Directory");

        initComponents();

        textOperation = new TextOperation(new CustomEnglishAnalyzer());
        pengindeksan = new Indexing(textOperation);
        pencarian = new Searching(textOperation);

        labelNotifikasi.setText(" ");
        labelProses.setText(" ");
        englishRadioButton.setSelected(true);
        progressBarStatus.setVisible(false);
        labelStatus.setVisible(false);
        labelHasil.setVisible(false);

        // Periksa kondisi basis data MySQL sudah nyala atau belum
        try {
            operasidb = new DatabaseOperation();
            // operasidb.buka();
            // operasidb.tutup(); // hanya periksa, langsung ditutup lagi
        } catch (Exception e){
            JOptionPane.showMessageDialog(rootPane, "No connection to database. Turn on MySQL Server.",
                    "LSI Search", JOptionPane.WARNING_MESSAGE);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {

        jPanel1 = new JPanel();
        jPanel5 = new JPanel();
        fieldCari = new JTextField();
        tombolCari = new JButton();
        jLabel2 = new JLabel();
        fieldLokasi = new JTextField();
        jLabel4 = new JLabel();
        labelNotifikasi = new JLabel();
        jPanel6 = new JPanel();
        indonesiaRadioButton = new JRadioButton();
        englishRadioButton = new JRadioButton();
        statusPanel = new JPanel();
        JSeparator statusPanelSeparator = new JSeparator();
        labelProses = new JLabel();
        progressBarStatus = new JProgressBar();
        labelStatus = new JLabel();
        jLabel1 = new JLabel();
        panelHasil = new JPanel();
        labelHasil = new JLabel();
        panelHasilCari = new JScrollPane();
        listHasilCari = new JList();
        jMenuBar1 = new JMenuBar();
        jMenu1 = new JMenu();
        menuCariBaru = new JMenuItem();
        jSeparator1 = new JPopupMenu.Separator();
        menuKeluar = new JMenuItem();
        jMenu2 = new JMenu();
        menuDaftarBerkas = new JMenuItem();
        menuTf = new JMenuItem();
        menuDf = new JMenuItem();
        jMenu3 = new JMenu();
        menuCara = new JMenuItem();
        menuTentang = new JMenuItem();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle(" Latent Semantic Indexing Search");
        setMinimumSize(new java.awt.Dimension(900, 500));

        jPanel5.setBackground(new java.awt.Color(102, 102, 102));

        fieldCari.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        fieldCari.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                fieldCariKeyTyped(evt);
            }
        });

        tombolCari.setForeground(new java.awt.Color(255, 255, 255));
        tombolCari.setIcon(new ImageIcon(getClass().getResource("/thesis/files/image/TombolCari - enabled.png"))); // NOI18N
        tombolCari.setBorder(BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
        tombolCari.setDisabledIcon(new ImageIcon(getClass().getResource("/thesis/files/image/TombolCari - disabled.png"))); // NOI18N
        tombolCari.setFocusPainted(false);
        tombolCari.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tombolCariActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Key words :");

        fieldLokasi.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        fieldLokasi.setDisabledTextColor(new java.awt.Color(102, 102, 102));
        fieldLokasi.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                fieldLokasiFocusGained(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel4.setForeground(new java.awt.Color(255, 255, 255));
        jLabel4.setText("Directory :");

        labelNotifikasi.setForeground(new java.awt.Color(255, 255, 255));
        labelNotifikasi.setText("notifikasi");

        GroupLayout jPanel5Layout = new GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel5Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(fieldLokasi, GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
                        .addGap(59, 59, 59)
                        .addComponent(jLabel2))
                    .addComponent(labelNotifikasi))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fieldCari, GroupLayout.PREFERRED_SIZE, 254, GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addComponent(tombolCari, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel4)
                    .addComponent(fieldLokasi, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
                    .addComponent(fieldCari, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
                    .addComponent(tombolCari, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelNotifikasi)
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel6.setBorder(BorderFactory.createTitledBorder(null, " Document Language ", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(51, 51, 51))); // NOI18N

        indonesiaRadioButton.setText("Bahasa Indonesia");
        indonesiaRadioButton.setFocusPainted(false);
        indonesiaRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                indonesiaRadioButtonActionPerformed(evt);
            }
        });

        englishRadioButton.setText("English Language");
        englishRadioButton.setFocusPainted(false);
        englishRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                englishRadioButtonActionPerformed(evt);
            }
        });

        GroupLayout jPanel6Layout = new GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(englishRadioButton)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                .addComponent(indonesiaRadioButton)
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(indonesiaRadioButton)
                    .addComponent(englishRadioButton))
                .addContainerGap(7, Short.MAX_VALUE))
        );

        labelProses.setHorizontalAlignment(SwingConstants.RIGHT);
        labelProses.setText("Proses");

        labelStatus.setText("Status");

        GroupLayout statusPanelLayout = new GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, GroupLayout.DEFAULT_SIZE, 922, Short.MAX_VALUE)
            .addGroup(GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                .addGap(2, 2, 2)
                .addComponent(labelStatus)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 719, Short.MAX_VALUE)
                .addComponent(labelProses)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(progressBarStatus, GroupLayout.PREFERRED_SIZE, 124, GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addGroup(statusPanelLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addComponent(labelProses)
                    .addComponent(progressBarStatus, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelStatus)))
        );

        jLabel1.setIcon(new ImageIcon(getClass().getResource("/thesis/files/image/Title.png"))); // NOI18N

        panelHasil.setBackground(new java.awt.Color(255, 255, 255));
        panelHasil.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));

        labelHasil.setBackground(new java.awt.Color(0, 0, 0));
        labelHasil.setFont(new java.awt.Font("Tahoma", 1, 11));
        labelHasil.setForeground(new java.awt.Color(255, 255, 255));
        labelHasil.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        labelHasil.setOpaque(true);

        listHasilCari.setFont(new java.awt.Font("Verdana", 0, 13));
        listHasilCari.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        listHasilCari.setSelectionBackground(new java.awt.Color(52, 83, 255));
        listHasilCari.setSelectionForeground(new java.awt.Color(255, 255, 255));
        listHasilCari.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listHasilCariMouseClicked(evt);
            }
        });
        listHasilCari.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                listHasilCariKeyTyped(evt);
            }
        });
        panelHasilCari.setViewportView(listHasilCari);

        GroupLayout panelHasilLayout = new GroupLayout(panelHasil);
        panelHasil.setLayout(panelHasilLayout);
        panelHasilLayout.setHorizontalGroup(
            panelHasilLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(labelHasil, GroupLayout.DEFAULT_SIZE, 920, Short.MAX_VALUE)
            .addComponent(panelHasilCari, GroupLayout.DEFAULT_SIZE, 920, Short.MAX_VALUE)
        );
        panelHasilLayout.setVerticalGroup(
            panelHasilLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(panelHasilLayout.createSequentialGroup()
                .addComponent(labelHasil, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addComponent(panelHasilCari, GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE))
        );

        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 457, Short.MAX_VALUE)
                .addComponent(jPanel6, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addComponent(statusPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(panelHasil, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel6, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 55, Short.MAX_VALUE))
                .addGap(13, 13, 13)
                .addComponent(jPanel5, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addComponent(panelHasil, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(0, 0, 0)
                .addComponent(statusPanel, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE))
        );

        jMenu1.setText("File");

        menuCariBaru.setText("New Search");
        menuCariBaru.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuCariBaruActionPerformed(evt);
            }
        });
        jMenu1.add(menuCariBaru);
        jMenu1.add(jSeparator1);

        menuKeluar.setText("Exit");
        menuKeluar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuKeluarActionPerformed(evt);
            }
        });
        jMenu1.add(menuKeluar);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("View");

        menuDaftarBerkas.setText("List of Files");
        menuDaftarBerkas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuDaftarBerkasActionPerformed(evt);
            }
        });
        jMenu2.add(menuDaftarBerkas);

        menuTf.setText("Term Frequency");
        menuTf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuTfActionPerformed(evt);
            }
        });
        jMenu2.add(menuTf);

        menuDf.setText("Document Frequency");
        menuDf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuDfActionPerformed(evt);
            }
        });
        jMenu2.add(menuDf);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Help");

        menuCara.setText("Usage");
        menuCara.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuCaraActionPerformed(evt);
            }
        });
        jMenu3.add(menuCara);

        menuTentang.setText("About");
        menuTentang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuTentangActionPerformed(evt);
            }
        });
        jMenu3.add(menuTentang);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // <editor-fold defaultstate="collapsed" desc="Penanganan Event">
    private void englishRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_englishRadioButtonActionPerformed
        englishRadioButton.setSelected(true);
        indonesiaRadioButton.setSelected(false);

        textOperation = new TextOperation(new CustomEnglishAnalyzer());
        pengindeksan = new Indexing(textOperation);
        pencarian = new Searching(textOperation);
    }//GEN-LAST:event_englishRadioButtonActionPerformed

    private void indonesiaRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_indonesiaRadioButtonActionPerformed
        indonesiaRadioButton.setSelected(true);
        englishRadioButton.setSelected(false);

        textOperation = new TextOperation(new CustomIndonesianAnalyzer());
        pengindeksan = new Indexing(textOperation);
        pencarian = new Searching(textOperation);
    }//GEN-LAST:event_indonesiaRadioButtonActionPerformed

    private void tombolCariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tombolCariActionPerformed
        tombolCari.transferFocus();
        String dir = fieldLokasi.getText();

        if (dir.equals("")) {
            labelNotifikasi.setText("Determine the location to search first.");
        } else {
            try {
                // Periksa basis data lagi
//                operasidb.buka();
//                operasidb.tutup(); // hanya periksa, langsung ditutup lagi

                proses = new Proses();
                t = new Thread(proses);
                t.start();
            } catch (Exception e){
                JOptionPane.showMessageDialog(rootPane, "No connection to database. Can't continue the process.",
                        "Failed", JOptionPane.ERROR_MESSAGE);
            }
        }
	}//GEN-LAST:event_tombolCariActionPerformed

    private void menuDaftarBerkasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuDaftarBerkasActionPerformed
        t = new Thread(new Runnable() {

            public void run() {

//                ImageIcon ikon = new ImageIcon("src/thesis/files/image/BlueButton.png");
//
//                FrameDaftarBerkas fdb = new FrameDaftarBerkas();
//                fdb.setIconImage(ikon.getImage());
//                fdb.setVisible(true);
            }
        });
        t.start();
    }//GEN-LAST:event_menuDaftarBerkasActionPerformed

    private void fieldLokasiFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_fieldLokasiFocusGained
        fieldLokasi.transferFocus();
        labelNotifikasi.setText(" ");
        if (pilihfolder.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File[] files = pilihfolder.getSelectedFiles();
            String pathLokasi = "";
            for (File file : files) {
                pathLokasi = file.getPath() + ";" + pathLokasi;
            }
            fieldLokasi.setText(pathLokasi);
        }
    }//GEN-LAST:event_fieldLokasiFocusGained

    private void menuTfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuTfActionPerformed
        t = new Thread(new Runnable() {

            public void run() {

//                ImageIcon ikon = new ImageIcon("src/thesis/files/image/BlueButton.png");
//
//                FrameTermFreq ft = new FrameTermFreq();
//                ft.setIconImage(ikon.getImage());
//                ft.setVisible(true);
            }
        });
        t.start();
    }//GEN-LAST:event_menuTfActionPerformed

    private void menuDfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuDfActionPerformed
        t = new Thread(new Runnable() {

            public void run() {

//                ImageIcon ikon = new ImageIcon("src/thesis/files/image/BlueButton.png");
//
//                FrameDocumentFreq fdoc = new FrameDocumentFreq();
//                fdoc.setIconImage(ikon.getImage());
//                fdoc.setVisible(true);
            }
        });
        t.start();
    }//GEN-LAST:event_menuDfActionPerformed

    private void menuCariBaruActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCariBaruActionPerformed

        fieldLokasi.setEnabled(true);
        fieldLokasi.setFocusable(true);
        fieldLokasi.setText("");

        fieldCari.setText("");

        listHasilCari.setModel(new DefaultListModel());
        labelStatus.setVisible(false);

        englishRadioButton.setSelected(true);
        indonesiaRadioButton.setSelected(false);

        labelHasil.setVisible(false);
        listHasilCari.setToolTipText("");

        textOperation = new TextOperation(new CustomEnglishAnalyzer());
        pengindeksan = new Indexing(textOperation);
        pencarian = new Searching(textOperation);
    }//GEN-LAST:event_menuCariBaruActionPerformed

    private void menuKeluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuKeluarActionPerformed
        System.out.println("\nThank you for using LSI Search, Bye.");
        JOptionPane.showMessageDialog(rootPane, "Thank you for using LSI Search.", "LSI Search", JOptionPane.INFORMATION_MESSAGE);
        System.exit(0);
    }//GEN-LAST:event_menuKeluarActionPerformed

    private void menuTentangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuTentangActionPerformed
        t = new Thread(new Runnable() {

            public void run() {

                ImageIcon ikon = new ImageIcon("src/thesis/files/image/BlueButton.png");

                FrameTentang ften = new FrameTentang();
                ften.setIconImage(ikon.getImage());
                ften.setVisible(true);
            }
        });
        t.start();
    }//GEN-LAST:event_menuTentangActionPerformed

    private void menuCaraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCaraActionPerformed
        t = new Thread(new Runnable() {

            public void run() {

//                ImageIcon ikon = new ImageIcon("src/thesis/files/image/BlueButton.png");
//
//                FrameCara fc = new FrameCara();
//                fc.setIconImage(ikon.getImage());
//                fc.setVisible(true);
            }
        });
        t.start();
    }//GEN-LAST:event_menuCaraActionPerformed

    private void fieldCariKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fieldCariKeyTyped
        char key = evt.getKeyChar();
        String dir = fieldLokasi.getText();

        if (key == '\n') {
            if (dir.equals("")) {
                labelNotifikasi.setText("Determine the location to search first.");
            } else {
                try {
                    // Periksa basis data lagi
                    // operasidb.buka();
                    // operasidb.tutup(); // hanya periksa, langsung ditutup lagi

                    proses = new Proses();
                    t = new Thread(proses);
                    t.start();
                } catch (Exception e){
                    JOptionPane.showMessageDialog(rootPane, "No connection to database. Can't continue the process.",
                            "Failed", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }//GEN-LAST:event_fieldCariKeyTyped

    @SuppressWarnings("rawtypes")
	private void listHasilCariKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_listHasilCariKeyTyped
        char karakter = evt.getKeyChar();
        if (karakter == '\n') {
            if (!listHasilCari.isSelectionEmpty()) {
                // Ambil teks pada listHasilCari yang dipilih
                String tekshtml = (String) listHasilCari.getSelectedValue();

                // Cari key (berisi String lokasi berkas) yang berisi value tekshtml
                int itung = 0;
                for (Map.Entry entri : maphasil.entrySet()) {
                    String lokasiberkas = (String) entri.getKey();
                    if (entri.getValue().equals(tekshtml)) {
                        System.out.println("Location[" + itung + "] : " + lokasiberkas);
                        bukaDefaultProgram(lokasiberkas);
                    }
                    itung++;
                }
            }
        }
    }//GEN-LAST:event_listHasilCariKeyTyped

    @SuppressWarnings("rawtypes")
	private void listHasilCariMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listHasilCariMouseClicked
        if (evt.getClickCount() == 2) {
            if (!listHasilCari.isSelectionEmpty()) {
                // Ambil teks pada listHasilCari yang dipilih
                String tekshtml = (String) listHasilCari.getSelectedValue();

                // Cari key (berisi String lokasi berkas) yang berisi value tekshtml
                int itung = 0;
                for (Map.Entry entri : maphasil.entrySet()) {
                    String lokasiberkas = (String) entri.getKey();
                    if (entri.getValue().equals(tekshtml)) {
                        System.out.println("Location[" + itung + "] : " + lokasiberkas);
                        bukaDefaultProgram(lokasiberkas);
                    }
                    itung++;
                }
            }
        }
    }//GEN-LAST:event_listHasilCariMouseClicked
    // </editor-fold>
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private JRadioButton englishRadioButton;
    private JTextField fieldCari;
    private JTextField fieldLokasi;
    private JRadioButton indonesiaRadioButton;
    private JLabel jLabel1;
    private JLabel jLabel2;
    private JLabel jLabel4;
    private JMenu jMenu1;
    private JMenu jMenu2;
    private JMenu jMenu3;
    private JMenuBar jMenuBar1;
    private JPanel jPanel1;
    private JPanel jPanel5;
    private JPanel jPanel6;
    private JPopupMenu.Separator jSeparator1;
    private JLabel labelHasil;
    private JLabel labelNotifikasi;
    private JLabel labelProses;
    private JLabel labelStatus;
    private JList listHasilCari;
    private JMenuItem menuCara;
    private JMenuItem menuCariBaru;
    private JMenuItem menuDaftarBerkas;
    private JMenuItem menuDf;
    private JMenuItem menuKeluar;
    private JMenuItem menuTentang;
    private JMenuItem menuTf;
    private JPanel panelHasil;
    private JScrollPane panelHasilCari;
    private JProgressBar progressBarStatus;
    private JPanel statusPanel;
    private JButton tombolCari;
    // End of variables declaration//GEN-END:variables
    private Proses proses;
    private Thread t;
    private JFileChooser pilihfolder;
    private Indexing pengindeksan;
    private Searching pencarian;
    private TextOperation textOperation;
    @SuppressWarnings("unused")
	private DatabaseOperation operasidb;
    private DoubleMatrix2D vd;
    private DoubleMatrix2D vk;
    private Map<String, String> maphasil;

    private void bukaDefaultProgram(String lokasiberkas) {
        Desktop desktop;
        if (Desktop.isDesktopSupported()) {
            desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.OPEN)) {
                File file = new File(lokasiberkas);
                try {
                    desktop.open(file);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(rootPane, "Program to open the file was not registered.",
                            "Failed", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    private int hitungJumlahFile(String path) {
        String[] paths = path.split(";");
        int jum = 0;
        for (int i = 0; i < paths.length; i++){
            File filefolder = new File(paths[i]);
            if (filefolder.isFile()){
                jum++;
            } else if (filefolder.isDirectory()){
                for (File files : filefolder.listFiles()){
                    jum += hitungJumlahFile(files.getPath());
                }
            }/*
            for (File f : filefolder.listFiles()){
                if (f.isFile()){
                    jum++;
                } else if (f.isDirectory()){
                    jum += hitungJumlahFile(f.getPath());
                }
            }*/
        }

        return jum;
    }


// <editor-fold defaultstate="collapsed" desc="Proses Background implements Runnable()">
    private class Proses implements Runnable {

        String lokasi;
        String katakunci;

        public void run() {
            long mulai = System.currentTimeMillis();
            int jumlahfile = hitungJumlahFile(fieldLokasi.getText());
            ImageIcon ikonSelesai = new ImageIcon("src/thesis/files/image/Check.png");

            katakunci = fieldCari.getText();
            if (katakunci == null ? "" != null : !katakunci.equals("")) {
                if (!fieldLokasi.isEnabled()) {
                    try {
                        matikan();
                        pencarian();
                        nyalakan();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else {
                    try {
                        if (jumlahfile == 1){
                            JOptionPane.showMessageDialog(rootPane, "Lack of documents. Use more than 1 document.",
                                    "Failed", JOptionPane.ERROR_MESSAGE);
                        } else {
                            System.out.println("Jumlah file : " + jumlahfile);

                            fieldLokasi.setEnabled(false);
                            fieldLokasi.setFocusable(false);

                            matikan();
                            pengindeksan();
                            pencarian();
                            nyalakan();
                        }
                        
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            } else {
                if (fieldLokasi.isEnabled()) {
                    try {
                        if (jumlahfile == 1){
                            JOptionPane.showMessageDialog(rootPane, "Lack of documents. Use more than 1 document.",
                                    "Failed", JOptionPane.ERROR_MESSAGE);
                        } else {
                            System.out.println("Total files : " + jumlahfile);

                            fieldLokasi.setEnabled(false);
                            fieldLokasi.setFocusable(false);

                            matikan();
                            pengindeksan();

                            System.out.println("Indexing finished.");

                            labelStatus.setIcon(ikonSelesai);
                            labelStatus.setText("Indexing finished.");
                            labelStatus.setBorder(new EmptyBorder(0,3,0,0));
                            labelStatus.setVisible(true);

                            nyalakan();
                        }
                        
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else {
                    
                    JOptionPane.showMessageDialog(rootPane, "Directory(ies) has been indexed. "
                            + "Enter a key word to search.", "LSI Search",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
            
            long selesai = System.currentTimeMillis();
            double menit = (double) ((selesai - mulai) / 1000) / 60;
            long detik = ((selesai - mulai) / 1000) % 60;
            DecimalFormat runtimeDF = new DecimalFormat("#");
            runtimeDF.setRoundingMode(RoundingMode.DOWN);
            System.out.println(runtimeDF.format(menit) + " Minutes " + detik + " Seconds");
        }

        public void pengindeksan() throws Exception {
            
            lokasi = fieldLokasi.getText();

            // Proses engindeksan
            labelProses.setText("Erasing database...");
            pengindeksan.pengindeksanBaru();

            labelProses.setText("Saving files...");
            String[] folder = lokasi.split(";");
            for (int i = 0; i < folder.length; i++) {
                System.out.println(folder[i]);
                pengindeksan.periksa(folder[i]);
            }

            labelProses.setText("Processing texts...");
            pengindeksan.indeksFile();

            labelProses.setText("Computing local weight...");
            pengindeksan.hitungTf();

            labelProses.setText("Computing global weight...");
            pengindeksan.hitungIdf();

            labelProses.setText("Computing term weight...");
            pengindeksan.hitungBobot();

            labelProses.setText("Saving term-document matrix...");
            pengindeksan.buatTermDocumentMatrix();

            labelProses.setText("Computing document vector...");
            vd = pengindeksan.hitungVektorDokumen();

        }

        public void pencarian() throws Exception {

            // Proses pencarian

            labelProses.setText("Processing key words...");
            pencarian.prosesKueri(katakunci);

            labelProses.setText("Computing query weight...");
            pencarian.hitungBobotKueri();

            labelProses.setText("Saving pseudo-document matrix...");
            pencarian.buatMatriksKueri();

            labelProses.setText("Computing query vector...");
            vk = pencarian.hitungVektorKueri();

            labelProses.setText("Computing cosine similarity...");
            DoubleMatrix2D sim = pencarian.cosineSimilarity(vk, vd);

            labelProses.setText("Displaying search results...");
            List<HasilCari> hasil = pencarian.urutkanHasil(sim);

            maphasil = pencarian.cetakHasilDb(hasil);
            List<String> list = new ArrayList<String>();
            list.addAll(maphasil.values());

            //System.out.println("\nHasil :");
            Object[] hasilcari = list.toArray();
            for (int i = 0; i < hasilcari.length; i++) {
                // Object h = hasilcari[i];
            }

            if (hasilcari.length != 0){
                labelHasil.setText("Documents retrieved.");
                labelHasil.setVisible(true);

                listHasilCari.setListData(hasilcari);
                listHasilCari.setToolTipText("Push ENTER or click 2x to open the file");
            } else {
                labelHasil.setText("No matching documents.");
                labelHasil.setVisible(true);

                listHasilCari.setListData(hasilcari);
                listHasilCari.setToolTipText("");
            }

            //pencarian.tampilkanHasil(hasil, katakunci);

            labelStatus.setIcon(null);
            labelStatus.setText(hasilcari.length + " search results");
            labelStatus.setVisible(true);
        }

        public void matikan() {
            ImageIcon ikonProses = new ImageIcon("src/thesis/files/image/Cancel.png");
            labelStatus.setIcon(ikonProses);
            labelStatus.setIconTextGap(4);
            labelStatus.setText("");
            labelStatus.setVisible(true);

            menuCariBaru.setEnabled(false);
            menuKeluar.setEnabled(false);
            menuDaftarBerkas.setEnabled(false);
            menuDf.setEnabled(false);
            menuTf.setEnabled(false);

            fieldCari.setFocusable(false);
            tombolCari.setEnabled(false);

            if (indonesiaRadioButton.isSelected()) {
                indonesiaRadioButton.setFocusable(false);
                englishRadioButton.setEnabled(false);
            }
            if (englishRadioButton.isSelected()) {
                englishRadioButton.setFocusable(false);
                indonesiaRadioButton.setEnabled(false);
            }

            progressBarStatus.setVisible(true);
            progressBarStatus.setIndeterminate(true);
        }

        public void nyalakan() {
            
            progressBarStatus.setIndeterminate(false);
            progressBarStatus.setVisible(false);
            labelProses.setText(" ");

            menuCariBaru.setEnabled(true);
            menuKeluar.setEnabled(true);
            menuDaftarBerkas.setEnabled(true);
            menuDf.setEnabled(true);
            menuTf.setEnabled(true);

            fieldCari.setFocusable(true);
            tombolCari.setEnabled(true);

            englishRadioButton.setEnabled(true);
            englishRadioButton.setFocusable(true);
            indonesiaRadioButton.setEnabled(true);
            indonesiaRadioButton.setFocusable(true);
        }
    }// </editor-fold>
}
